package com.bungarus.sdk.codec;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelOutboundHandlerAdapter;
import io.netty.channel.ChannelPromise;
import io.netty.handler.codec.http.*;
import org.apache.log4j.Logger;

/**
 * Created by tang on 2019/1/8.
 */
public class ProtobufWrappedWithHttpReqEncoder extends ChannelOutboundHandlerAdapter {
    Logger logger = Logger.getLogger(ProtobufWrappedWithHttpReqEncoder.class);
    @Override
    public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) throws Exception {
        if(msg instanceof ByteBuf) {
            ByteBuf content = (ByteBuf)msg;
            // Prepare the HTTP request.
            DefaultFullHttpRequest request = new DefaultFullHttpRequest(
                    HttpVersion.HTTP_1_1, HttpMethod.POST, "/msg");
            request.headers().set(HttpHeaderNames.HOST, "im.bungarus.com");
            request.headers().set(HttpHeaderNames.USER_AGENT, "Bungarus/1.0.0");
            request.headers().set(HttpHeaderNames.CONNECTION, HttpHeaderValues.KEEP_ALIVE);
            request.headers().set(HttpHeaderNames.CONTENT_TYPE, HttpHeaderValues.BYTES);
            request.headers().set(HttpHeaderNames.CONTENT_LENGTH, content.readableBytes());
            request.headers().set(HttpHeaderNames.ACCEPT_ENCODING, "gzip, deflate");

            request.content().writeBytes(content);

            ctx.writeAndFlush(request, promise);
        }
        else {
            super.write(ctx, msg, promise);
        }
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        super.exceptionCaught(ctx, cause);
    }
}
